const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

// 安全处理正则表达式
const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

exports.main = async (event) => {
  const { action, courseId, teacherId, weekNumber, studentName,studentId } = event;
  const db = cloud.database();
  const _ = db.command;

  try {
    if (action === 'getStudents') {
      console.log('进入获取学生列表分支');
      console.log('courseId:', courseId);
      console.log('teacherId:', teacherId);
      console.log('weekNumber:', weekNumber);
      console.log('studentName:', studentName);
      // 1. 权限验证 - 使用try-catch增强健壮性
      try {
        const course = await db.collection('courses').doc(courseId).get();
        if (!course.data || course.data.teacherId !== teacherId) {
          return { code: 403, msg: '无权限访问该课程' };
        }
      } catch (error) {
        console.error('权限验证失败:', error);
        return { code: 403, msg: '课程不存在或无权限访问' };
      }
 
      // 2. 优化查询 - 使用聚合操作减少数据库请求次数
      const courseStudentsRes = await db.collection('course_students')
        .where({ courseId })
        .limit(100) // 添加限制，避免数据过多
        .get();

      // 3. 处理学生ID列表
      const studentIds = courseStudentsRes.data.map(x => x.studentId);
      if (studentIds.length === 0) return { code: 200, data: [] };

      // 4. 构建查询条件 - 优化正则表达式查询
      const filter = { _id: _.in(studentIds) };
      if (studentName && studentName.trim() !== '') {
        filter.name = db.RegExp({
          regexp: `.*${escapeRegExp(studentName.trim())}.*`,
          options: 'i'
        });
      }
  

      // 5. 获取学生数据 - 添加字段投影和限制
      const studentsRes = await db.collection('students')
        .where(filter)
        .field({
          name: true,
          studentId: true,
          // 添加其他需要的字段
        })
        .limit(100) // 添加限制，避免数据过多
        .get();
      console.log('studentsRes:',studentsRes)
  
      // 6. 单独查询表现数据 - 只查询需要的字段
      const performanceRes = await db.collection('performance')
        .where({ 
          courseId, 
          weekNumber: Number(weekNumber),
          studentId: _.in(studentsRes.data.map(s => s._id))
        })
        .field({
          studentId: true,
          attendance: true,
          answer: true,
          question: true
        })
        .get();
         // 7. 合并表现数据 - 使用Map优化查找性能
      const performanceMap = {};
      performanceRes.data.forEach(p => {
        performanceMap[p.studentId] = p;
      });
      
      return {
        code: 200,
        data: studentsRes.data.map(student => {
          const performance = performanceMap[student._id] || {};
          return {
            ...student,
            attendance: performance.attendance || 0,
            answer: performance.answer || 0,
            question: performance.question || 0,
            total: (performance.attendance || 0) + 
                   (performance.answer || 0) + 
                   (performance.question || 0)
          };
        })
      };

    }else if (action === 'test') {
      console.log('进入测试分支');
      return { code: 200, data: 'test张丽' };

    } else if (action === 'getSingleRecord') {
    /*
    功能：获取单个学生的表现记录
    输入：
    courseId: 课程ID
    studentId: 学生ID
    weekNumber: 周数
    输出：
    学生基础信息
    表现记录
    **/
      // 1.参数校验增强
    if (!courseId || !studentId || !weekNumber) {
      return { code: 400, msg: '缺少必要参数' };
    }
    // const courseA = await db.collection('courses').doc(courseId).get();
    // 使用复合查询条件
     console.log('getSingleRecord--->courseId:',courseId)
     console.log('getSingleRecord--->studentId:',studentId)
     console.log('getSingleRecord--->weekNumber:',weekNumber)
     const recordRes = await db.collection('performance')
     .where({
       courseId,
       studentId,
       weekNumber
     })
     .get();
     console.log('getSingleRecord--->recordRes:',recordRes)
     const studentRes = await db.collection('students').doc(studentId).get();
     console.log('getSingleRecord--->studentRes:',studentRes)
     return {
      code: 200,
      data: {
        studentInfo: studentRes.data,
        performance: recordRes.data[0] || {
          attendance: 0,
          answer: 0,
          question: 0
        }
      }
    };
  }


    // ... 其他操作保持不变
  } catch (err) {
    console.error('云函数执行失败：', err);
    return { code: 500, msg: '服务器内部错误' };
  }
};